//
//  NSArray+WLBlock.h
//  CeXi
//
//  Created by 录音转文字助手 on 2017/7/12.
//  Copyright © 2017年 wangLiang. All rights reserved.
//

#import "NSArray+WLBlock.h"

@implementation NSArray (WLBlock)

- (void)each:(void (^)(id, NSInteger idx))block {
    for (int i = 0; i < self.count ; i++) {
        block([self objectAtIndex:i],i);
    }
}

- (NSArray *)map:(id (^)(id object))block {
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:self.count];
    for (id object in self) {
        id mappedObject = block(object);
        if(mappedObject) {
            [array addObject:mappedObject];
        }
    }
    return array;
}

- (NSArray *)select:(BOOL (^)(id object))block {
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:self.count];
    for (id object in self) {
        if (block(object)) {
            [array addObject:object];
        }
    }
    return array;
}
- (id)selectItem:(BOOL (^)(id object))block{
    id data = nil;
    for (id object in self) {
        if (block(object)) {
            data = object;
            break;
        }
    }
    return data;
}

- (NSArray *)reject:(BOOL (^)(id object))block {
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:self.count];
    for (id object in self) {
        if (block(object) == NO) {
            [array addObject:object];
        }
    }
    return array;
}
- (id)rejectItem:(BOOL (^)(id object))block{
    id data = nil;
    for (id object in self) {
        if (block(object) == NO) {
            data = object;
            break;
        }
    }
    return data;
}
- (NSArray *)sort {
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES];
    return [self sortedArrayUsingDescriptors:@[sortDescriptor]];
}

- (id)reduce:(id(^)(id accumulator, id object))block {
    return [self reduce:nil withBlock:block];
}

- (id)reduce:(id)initial withBlock:(id(^)(id accumulator, id object))block {
    id accumulator = initial;
    
    for(id object in self)
        accumulator = accumulator ? block(accumulator, object) : object;
    
    return accumulator;
}
@end
